package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.userMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;

import com.sky.service.user.userService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description userServiceImpl
 * @Author luohai
 * @Date 2024-10-13
 */
@Service
public class userServiceImpl implements userService {

    public static final String WX_LOGIN ="https://api.weixin.qq.com/sns/jscode2session";
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private userMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private MerchantMapper merchantMapper;

    /**
     * 用户登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO userLogin(UserLoginDTO userLoginDTO) {
        //获取
        String openId =getOpenId(userLoginDTO.getCode());

        if (StringUtils.isEmpty(openId)){
            throw new UserNotLoginException("用户登录失败");
        }

        User user= userMapper.selectByOpenId(openId);
        if (user==null){
            user = User.builder().openid(openId).createTime(LocalDateTime.now()).build();
            userMapper.save(user);
        }

        //如果查询到，根据id生成token，返回给前端
        Map<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        Merchant merchant=merchantMapper.selectById(1l);

        String location = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal delivoryCost = MapUtils.getDelivoryCost(location, userLoginDTO.getLocation());

        //构建返回值
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(1l)
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(delivoryCost)
                .build();
        return userLoginVO;
    }

    private String getOpenId(String code) {
        Map<String,String> wxMap=new HashMap<>();
        wxMap.put("appid",weChatProperties.getAppid());
        wxMap.put("secret",weChatProperties.getSecret());
        wxMap.put("js_code",code);
        wxMap.put("grant_type","authorization_code");
        String s = HttpClientUtil.doGet(WX_LOGIN, wxMap);
        Map map = JSONObject.parseObject(s, Map.class);
        return map.get("openid").toString();
    }

}


